/**
 * @author Cator Vee  hi@catorv.com
 */
import { mixin } from '../utils'
import { buildUrl, queryString, urlEncode } from '../utils/url'
import { app } from '../'
import { storage } from './data'
import env from '../lib/env'

const STORAGE_KEY = 'wechat-data'
const TYPE_UPDATE = '@@WECHAT_MP/UPDATE'
const NAMESPACE = 'wechat'

const location = window.location

let inited = false
let data
let config

let ali = {
  init: function (_params) {
    if (inited) {
      return Promise.resolve()
    }
    inited = true
    // 没有user_id => 1.授权页面 , 2. 授权回调页面
    if (!data.userid) {
      let query = queryString()
      let url
      const {access_token: accessToken, user_id: userid} = query
      if (accessToken && userid) {
        // 经过授权页面, 未经过授权回调页面
        app.updateContext({userid, userInfo: JSON.parse(query.userinfo)})
        storage.set(STORAGE_KEY, {userid})
        delete query.access_token
        delete query.user_id
        delete query.scope
        delete query.userinfo
        url = buildUrl(query)
      } else {
        // 未经过授权页面
        url = config.oauth.replace('{state}', urlEncode(location.href))
      }
      location.href = url
      return Promise.reject(new Error())
    }
  }
}

export function enbaleAliPaySupport (opts = {}) {
  config = app.config.ali || {}
  const namespace = opts.namespace || NAMESPACE
  const initialState = data = mixin({
    ready: true,
    appId: config.appId
  }, storage.get(STORAGE_KEY) || {})

  const extraReducers = {
    [namespace] (state = initialState, {type, payload}) {
      let ret
      switch (type) {
        case TYPE_UPDATE:
          ret = data = {...state, ...payload}
          storage.set(STORAGE_KEY, ret)
          if (payload.userid) {
            app.updateContext({userid: data.userid})
          }
          break
        default:
          ret = state
          break
      }
      return ret
    }
  }
  if (env.alipay) {
    app.preprocessing = app.preprocessing.then(() => ali.init(null, config))
  }
  return {extraReducers}
}
